<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/admin/dashboard">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加分类的对话框 -->
    <el-dialog
      :title="isAdd ? '添加分类' : '修改分类'"
      :visible.sync="dialogVisible"
      width="33%"
      @close="addDialogClosed"
    >
      <!-- 内容的主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        @submit.native.prevent
      >
        <el-form-item label="分类名" prop="name">
          <el-input
            ref="getNameFocus"
            v-model="addForm.name"
            @keyup.enter.native="addSort"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span solt="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addSort" native-type="submit"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <!-- 卡片 -->
    <el-card class="category-container">
      <!-- 按钮 -->
      <el-row>
        <!-- 添加 -->
        <el-col :span="8">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-circle-plus-outline"
            @click="handleAdd"
          >
            添加分类
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="multiDeleteVisible = true"
            v-if="multipleSelectionFlag"
          >
            批量删除
          </el-button>
          <el-dialog
            :visible.sync="multiDeleteVisible"
            title="提示"
            width="33%"
          >
            <span>确定要删除吗？</span>
            <span slot="footer">
              <el-button type="primary" @click="multiDelete">确定</el-button>
              <el-button @click="multiDeleteVisible = false">取消</el-button>
            </span>
          </el-dialog>
        </el-col>
        <!-- 搜索功能 -->
        <el-col :span="8" :offset="8">
          <span class="font-sort">查找分类</span>
          <el-input
            size="small"
            placeholder="请输入搜索关键字"
            prefix-icon="el-icon-search"
            v-model="search"
            clearable
          ></el-input>
          <!-- <el-button type="primary" size="mini"> 搜索 </el-button> -->
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        ref="selectTable"
        border
        stripe
        :data="searchSort.slice((page - 1) * size, page * size)"
        show-summary
        max-height="700px"
        :default-sort="{ prop: 'sort_updatedTime', order: 'descending' }"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="56px"
          align="center"
          padding-left="0"
        ></el-table-column>
        <el-table-column
          label="序号"
          type="index"
          :index="getIndex"
          width="50px"
          align="center"
        ></el-table-column>
        <el-table-column
          label="分类名"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          label="文章量"
          prop="sort_articles"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column
          label="点击量"
          prop="sort_views"
          align="center"
          sortable
        ></el-table-column>
        <!-- 自定义模板 -->
        <el-table-column label="日期" align="center" sortable>
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{
              scope.row.sort_updatedTime
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleChange(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDel(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="page"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchSort.length"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Category",
  data() {
    return {
      sort: [],
      search: "",
      selectSort: [],
      page: 1,
      size: 10,
      total: 0,
      //控制对话框的显示与隐藏（添加）
      dialogVisible: false,
      isAdd: true,
      addForm: {
        name: "",
      },
      id: null,
      addFormRules: {
        name: [
          { required: true, message: "请输入分类名", trigger: "blur" },
          { min: 1, max: 8, message: "长度在1-8个字符之间", trigger: "blur" },
        ],
      },

      multipleSelectionFlag: false, //批量删除按钮是否显示

      multiDeleteVisible: false, //批量删除的弹框是否弹出
      multipleSelection: "", //用来储存select框选中的数据
    };
  },
  created() {
    this.getSorts();
  },
  computed: {
    //实现单页模糊搜索
    searchSort() {
      const search = this.search;
      if (search) {
        return this.sort.filter((data) => {
          return Object.keys(data).some((key) => {
            return String(data[key]).toLowerCase().indexOf(search) > -1;
          });
        });
      }
      return this.sort;
    },
  },
  methods: {
    getSorts() {
      this.$http.get("/category/getCategorys").then((res) => {
        const { code, result } = res;
        // console.log(res);
        if (code == 0) {
          this.sort = result.data[0];
        }
      });
    },
    getIndex(index) {
      //此处的 index 值是对应列的每一行的索引值（0、1、2、3......）
      // console.log(index);
      const page = this.page;
      const size = this.size;
      return (page - 1) * size + index + 1;
    },
    handleSizeChange(size) {
      // console.log(size);
      this.size = size;
      // this.getSorts();
    },
    handleCurrentChange(page) {
      // console.log(page);
      this.page = page;
      // this.getSorts();
    },
    //打开添加分类的对话框
    handleAdd() {
      this.isAdd = true;
      this.dialogVisible = true;

      //自动获焦
      this.$nextTick(() => {
        this.$refs.getNameFocus.focus();
        this.$refs.addFormRef.clearValidate();
      });
    },
    //打开修改分类的对话框
    handleChange(id) {
      // console.log(id);
      this.id = id;
      this.isAdd = false;
      this.dialogVisible = true;

      //发送请求、自动获焦、移除表单项校验结果
      this.$nextTick(() => {
        this.$http.get(`/category/getCategory/${id}`).then((res) => {
          // console.log(res.result[0][0].name);
          // console.log(res.result[0].name);
          this.addForm.name = res.result[0][0].name;
        });
        this.$refs.getNameFocus.focus();
        this.$refs.addFormRef.clearValidate();
      });
    },
    //关闭对话框时，监听添加对话框的关闭事件，重置添加表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //点击按钮，添加新分类
    addSort() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;

        // 校验通过
        if (this.isAdd) {
          // 新增
          await this.$http
            .post("/category/addCategory", this.addForm)
            .then((res) => {
              console.log(res);
              const { code, message } = res;
              if (code == 0) {
                this.$message({
                  type: "success",
                  message: "添加成功",
                  duration: "1000",
                });
              } else {
                this.$message({
                  type: "error",
                  message: "添加失败",
                  duration: "1000",
                });
              }
            });
        } else {
          // 修改
          await this.$http
            .put("/category/changeCategory/" + this.id, this.addForm)
            .then((res) => {
              const { code, message } = res;
              if (code == 0) {
                //提示信息
                this.$message({
                  type: "success",
                  message: "修改成功",
                  duration: "1000",
                });
              } else {
                this.message({
                  type: "error",
                  message: "修改失败",
                  duration: "1000",
                });
              }
            });
        }
        //隐藏添加分类的对话框
        this.dialogVisible = false;
        //重新获取分类列表数据
        this.getSorts();
      });
    },
    handleDel(id) {
      // console.log(id);//当前行数据的id值
      this.$confirm("此操作将删除该分类，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("/category/deleteCategory/" + id).then((res) => {
            let { code, message } = res;
            if (code == 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
                duration: "1000",
              });
              //更新数据列表
              this.getSorts();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            duration: "1000",
          });
        });
    },
    //勾选表格
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.multipleSelectionFlag = true;
      // console.log(val); //用户勾选的数据，数组形式
      if (this.multipleSelection.length == 0) {
        this.multipleSelectionFlag = false;
      }
    },
    //批量删除
    multiDelete() {
      this.multiDeleteVisible = false;
      let checkArr = this.multipleSelection;
      if (checkArr) {
        let params = [];
        checkArr.forEach((item) => {
          params.push(item.id);
        });
        this.$http.post("/category/deleteCategorys", params).then((res) => {
          // console.log(res);
          const { code, message } = res;
          if (code == 0) {
            this.getSorts();
            this.$message({
              type: "success",
              message: "批量删除成功",
              duration: "1000",
            });
          } else {
            this.$message({
              type: "info",
              message: "批量删除失败",
              duration: "1000",
            });
          }
        });
        this.$nextTick(() => {
          this.$refs.selectTable.clearSelection();
        });
      }
    },
  },
};
</script>

<style lang="stylus" scoped>
.category-container
  margin-top 20px
  height 800px
  min-width 1100px
  .font-sort
    color #606266
    font-size 14px
    font-weight: 700
    font-family: Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Arial,sans-serif
    margin-right 10px
  .el-input
    width 50%
    margin-right 10px
  .el-table
    margin 10px 0
    /* 文章分类标题行背景色 */
    th.el-table__cell
      background-color #f5f7fa
    /* 文章分类表头字体样式 */
    .has-gutter
      color #909399
      font-weight 600
      font-size 14px
      font-family Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Arial,sans-serif
/* 标题行与表格内的全选框不能对齐 */
.el-table--border .el-table__cell:first-child .cell
  padding-left 0
</style>
